package com.njupt.backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: wujiaming
 * @CreateTime: 2024/12/16 14:53
 * @Description: 90. 子集 II
 * @Version: 1.0
 *
 */


public class SubsetsWithDup_90 {

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<Integer> result = new LinkedList<>();
        List<List<Integer>> results = new ArrayList<>();
        boolean[] used = new boolean[nums.length];
        Arrays.sort(nums);
        int startIndex = 0;
        traceBacking(startIndex,nums,used,results,result);

        return results;
    }

    private void traceBacking(int startIndex, int[] nums, boolean[] used, List<List<Integer>> results, List<Integer> result) {
        results.add(new ArrayList<>(result));
        if(startIndex == nums.length){
            return;
        }
        for (int i = startIndex; i < nums.length ; i++) {
            if(i>0 &&  nums[i] == nums[i-1] && used[i-1] ==false){
                continue;
            }
//            if(i>startIndex &&  nums[i] == nums[i-1]){
//                continue;
//            }

            result.add(nums[i]);
            used[i] = true;
            traceBacking(i+1,nums,used,results,result);
            result.remove(result.size()-1);
            used[i] = false;
        }
    }

    public static void main(String[] args) {
        int[] nums = {1,2,2};
        SubsetsWithDup_90 test = new SubsetsWithDup_90();
        List<List<Integer>> results = test.subsetsWithDup(nums);
        System.out.println(results);
    }
}
